package SingleInstanceApplication;

import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class AppStarter {
	private String HOST = "localhost";
	private int PORT = 2222;

	public static void main(String[] args) {
		new AppStarter();
	}

	public AppStarter() {
		// try to connect to server
		if (findExisting()) {
			JOptionPane.showMessageDialog(null, "Another instance of this program\nis already running\nClick OK to Quit...");
			System.exit(0);
		}

		// start detecting server thread
		new Thread(new DetectForNew()).start();
		// start app instance
		JFrame app = new MyApp();
		app.setVisible(true);
	}

	private boolean findExisting() {
		Socket client;
		try {
			System.out.println("creating socket");
			client = new Socket(HOST, PORT);
			System.out.println("Connection accepted by already running app");
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			System.out.println("Not Found - Not running");
			return false;
		}
	}

	class DetectForNew implements Runnable {
		ServerSocket serverSocket;

		@Override
		public void run() {
			System.out.println("detect thread started");
			try {
				serverSocket = new ServerSocket(PORT);
				while (true) {
					serverSocket.accept();
					System.out.println("multiple run attempt detected");
				}
			} catch (Exception e) {
				System.out.println("detect thread terminated ");
				e.printStackTrace();
			}
		}
	}

}

class MyApp extends JFrame {
	MyApp app;
	public static void maximize(){
		
	}
	public MyApp() {
		setSize(200, 300);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}
}